package com.wzq.tools.interconversion;

import org.assertj.core.util.Lists;
import org.springframework.cglib.beans.BeanMap;

import java.util.HashMap;
import java.util.List;
import java.util.Map;

/**
 * Map与Object对象的相互转换
 *
 * @author weizq
 * @since 2021/2/25
 */
public class MapAndObjectInterconversion<T> {

    /**
     * 将对象装换为map
     *
     * @param bean 转换对象
     * @return java.util.Map<java.lang.String, java.lang.Object>
     * @author weizq
     * @since 2021/2/25
     */
    public static <T> Map<String, Object> beanToMap(T bean) {
        Map<String, Object> map = new HashMap<String, Object>();
        if (bean != null) {
            BeanMap beanMap = BeanMap.create(bean);
            for (Object key : beanMap.keySet()) {
                map.put(key + "", beanMap.get(key));
            }
        }
        return map;
    }

    /**
     * 将map装换为javabean对象
     *
     * @param map  转换的map
     * @param bean 要转换成的对象
     * @return T 要转换成的类型
     * @author weizq
     * @since 2021/2/25
     */
    public static <T> T mapToBean(Map<String, Object> map, T bean) {
        BeanMap beanMap = BeanMap.create(bean);
        beanMap.putAll(map);
        return bean;
    }

    /**
     * 将List<T>转换为List<Map<String, Object>>
     *
     * @param objList 转换的对象
     * @return java.util.List<java.util.Map < java.lang.String, java.lang.Object>>
     * @author weizq
     * @since 2021/2/25
     */
    public static <T> List<Map<String, Object>> objectsToMaps(List<T> objList) {
        List<Map<String, Object>> list = Lists.newArrayList();
        if (objList != null && objList.size() > 0) {
            Map<String, Object> map = null;
            T bean = null;
            for (int i = 0, size = objList.size(); i < size; i++) {
                bean = objList.get(i);
                map = beanToMap(bean);
                list.add(map);
            }
        }
        return list;
    }

    /**
     * 将List<Map<String,Object>>转换为List<T>
     *
     * @param maps  转换的对象
     * @param clazz 要转换从对象类型
     * @return java.util.List<T>
     * @throws InstantiationException 实例化异常
     * @throws IllegalAccessException 无法访问指定的方法
     * @author weizq
     * @since 2021/2/25
     */
    public static <T> List<T> mapsToObjects(List<Map<String, Object>> maps, Class<T> clazz) throws InstantiationException, IllegalAccessException {
        List<T> list = Lists.newArrayList();
        if (maps != null && maps.size() > 0) {
            Map<String, Object> map = null;
            T bean = null;
            for (int i = 0, size = maps.size(); i < size; i++) {
                map = maps.get(i);
                bean = clazz.newInstance();
                mapToBean(map, bean);
                list.add(bean);
            }
        }
        return list;
    }

}
